require("babel-polyfill");
import Gun from "gun/gun";
import { User as GunUser } from "gun/sea";

const _promisify = (obj, method, args) => {
  function handler(resolve, reject) {
    obj[method](...args, cb => {
      if (cb.lack) return;
      if (cb.err) {
        reject(new Error(cb.err));
        return;
      }
      resolve();
    });
  }

  return new Promise(handler.bind(this));
};

class User {
  constructor() {
    // TODO: Singleton to configure and inject GUN.
    this._gun = Gun(); // { localStorage: false, radisk: false })
    this._gunuser = this._gun.user(); //.recall({ sessionStorage: false });
  }

  async create(alias, password) {
    if (!alias) throw new Error("Invalid alias");
    if (!password) throw new Error("Invalid password");
    return _promisify(this._gunuser, "create", [alias, password]).then(() => {
      return this.auth(alias, password);
    });
  }

  async auth(alias, password) {
    if (!alias) throw new Error("Invalid alias");
    if (!password) throw new Error("Invalid password");
    return _promisify(this._gunuser, "auth", [alias, password]).then(() => {
      if (!this._gunuser.is) throw new Error("Authentication failed");
      return this._gunuser.is;
    });
  }
}

export default User;
